package shared;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import server.ClientObject;

import client.ClientEvent;
import client.ClientListener;

public class HandlerThread extends Thread
{
	protected Socket connection;
	
	protected ObjectInputStream streamIn;
	protected ObjectOutputStream streamOut;
	
	/**
	 * Open Input and Output streams of connection
	 * @return TRUE if successful
	 */
	protected boolean openStreams()
	{
		if(connection == null)
		{
			return false;
		}
		
		try 
		{
			streamOut = new ObjectOutputStream(connection.getOutputStream());
			streamIn = new ObjectInputStream(connection.getInputStream());
			return true;
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			// TODO: Delegate to a Error Handler
			e.printStackTrace();
			return false;
		}
		
	}
	
	/**
	 * Stop input and output streams
	 * @return TRUE if successful
	 */
	protected boolean stopStreams()
	{
		try
		{
			if(streamOut != null) streamOut.close();
			if(streamIn != null) streamIn.close();
			
			return true;
		}
		catch(IOException io)
		{
			// TODO: Delegate to a Error Handler
			return false;
		}
	}
	
	/**
	 * Check whether Socket can receive 
	 * @return TRUE, if able to receive
	 */
	protected boolean canReceive()
	{
		if((connection != null && streamIn != null) && connection.isConnected() && !connection.isInputShutdown())
		{
			return true;
		}
		
		return false;
	}
	
	/**
	 * Check whether Socket can send 
	 * @return TRUE, if able to send
	 */
	protected boolean canSend()
	{
		if((connection != null && streamOut != null) && connection.isConnected() && !connection.isOutputShutdown())
		{
			return true;
		}
		
		return false;
	}
	
	/**
	 * Send an object
	 * @param obj
	 */
	protected void send(Object obj)
	{
		if(!canSend()) return;  // TODO: Implement Exception class
		
		try
		{
			streamOut.writeObject(obj.toString());
			streamOut.flush();
		}
		catch(IOException io)
		{
			// TODO: Delegate to a Error Handler
		}
	}
	
	/**
	 * Send an object
	 * @param obj
	 */
	protected void sendObject(Object obj)
	{
		if(!canSend()) return;  // TODO: Implement Exception class
		
		try
		{
			streamOut.writeObject(obj);
			streamOut.flush();
		}
		catch(IOException io)
		{
			// TODO: Delegate to a Error Handler
		}
	}

}
